#!usr/bin/env python3
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,BooleanField,SubmitField,Field,Label
from wtforms.widgets import Input,SubmitInput,HTMLString, html_params
from wtforms.validators import DataRequired,Length,Email,EqualTo,Regexp
from wtforms import ValidationError
from ..models import User,Role
from werkzeug.utils import escape,text_type
from config import getLang #获取语言包的函数 getLang(key,args)
from app import const
class ButtonInput(SubmitInput):
	input_type = "button"

class ButtonWidget(object): #自定义一个input组件
	def __call__(self,field,**kwargs):
		if field.name is not None:
			kwargs.setdefault("name",field.name)			
		kwargs.setdefault("type",field.btype)
		kwargs.setdefault('id',field.id)
		kwargs.setdefault("value",field.value)
		return HTMLString("<input %s>"%(html_params(**kwargs)))
	
class NoneLabel(Label):
	def __call__(self,**kwargs):
		return ""		

class InputButtonField(Field):
	widget = ButtonWidget()
	"""
	@params value 按钮的标签
	@params text  按钮的文本

	"""
	def __init__(self,value="按钮",text="btn",btype="button",**kwargs):
		super(InputButtonField, self).__init__(**kwargs)
		self.type = "SubmitField"
		self.btype = btype
		self.value = value
		self.text = text
		#self.label = NoneLabel("Null",text="")


EMAIL_LEN = const.EMAIL_LEN
USER_MIN = const.USER_MIN
USER_MAX = const.USER_MAX
PSW_MIN = const.PSW_MIN
PSW_MAX = const.PSW_MAX

emailMsg = getLang("emailMsg")

class LoginFrom(FlaskForm):#登陆表单
	email = StringField(getLang('email',EMAIL_LEN),validators = [DataRequired(),Length(1,EMAIL_LEN),Email(emailMsg)])
	password = PasswordField(getLang('psw',PSW_MIN,PSW_MAX),validators=[DataRequired()])
	remenber_me = BooleanField(getLang('keepLogin'))
	submit = SubmitField(getLang('login'))
	#register = InputButtonField(value="register")	

class RegisterForm(FlaskForm): #注册表单
	username = StringField(getLang('uname',USER_MIN,USER_MAX),validators=[
		DataRequired(getLang('userMsg')),
		Length(USER_MIN,USER_MAX,getLang('userLenTip',USER_MIN,USER_MAX)),
		Regexp('^[^0-9]',0,getLang("unameLegTips")),#设置用户名不能以数字开头 
		]
		)

	email = StringField(getLang('email',EMAIL_LEN),validators=[
		DataRequired(),
		Length(1,EMAIL_LEN),Email(emailMsg)])

	password = PasswordField(getLang('psw',PSW_MIN,PSW_MAX),validators=[
		DataRequired(),
		EqualTo("verify_psw",getLang('pswVerifyMsg')),
		Length(PSW_MIN,PSW_MAX,getLang('pswLenTip',PSW_MIN,PSW_MAX))
		])
	verify_psw = PasswordField(getLang('pswAgain',PSW_MIN,PSW_MAX),validators=[DataRequired()])
	submit = SubmitField(getLang('registe'))

	#自定义的验证函数 validate_ 开头并且后面跟着字段名就好字段执行验证

	def validate_email(self,field): #证email是否已经注册
	 	if User.query.filter_by(email=field.data).first():
	 	 	raise ValidationError(getLang('emailRegister')) 
	 	
	def validate_username(self,field):#验证username是否已经注册
		if User.query.filter_by(username=field.data).first():
			raise ValidationError(getLang('userRegister')) 